package com.chookss.home.tuwen;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.aliyun.svideo.common.utils.NetUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.base.Token;
import com.chookss.home.document.DocumentSearchActivity;
import com.chookss.home.entity.TuwenTypeEntity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.video.VideoNewCatesActivity;
import com.chookss.video.VideoSearchActivity;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.TuwenBottomDialog;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PublishTuwensActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_iv)
    ImageView commonRightIv;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout commonRightIvLl;
    @BindView(R.id.llAdd)
    LinearLayout llAdd;
    @BindView(R.id.edTitle)
    EditText edTitle;
    @BindView(R.id.rlDelete)
    RelativeLayout rlDelete;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.tvDirectory)
    TextView tvDirectory;
    @BindView(R.id.ivBg)
    View ivBg;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.ivChoice2)
    ImageView ivChoice2;

    private Adapter adapter;
    private List<TuwenTypeEntity> list = new ArrayList<>();
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private int shareFlag = 1;
    private int index = -1;
    private boolean sort = false;//默认排序是往上插入false是往下插入
    private boolean isEdit = false;//默认不是编辑模式，true是编辑模式 选择后删除当前item
    private int picInt = 0;//待上传的图片总数
    private int isUpload = 0;//1发布中 2按下发布按钮但是图片还未传成功 等待图片结束再发布  3发布成功4发布失败
    private String id = "", mainCode = "";//新增是空，有值说明要修改
    private String directoryCode = "";//目录code
    private boolean isPreview = false;//true开启预览模式
    private boolean dataNoShare = true;//文档或者视频有不能分享的
    private int saveTag = 0;//0右上角预览暂存 1普通暂存2按下返回键了保存并退出

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_tuwen);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        NavigationTools.saveUseRecord(this, "2", "16");
        mainCode = getIntent().getStringExtra("mainCode");
        commonTitleTxt.setText("发布");
        commonRightIv.setBackgroundResource(R.drawable.iv_preview);
        commonRightIvLl.setVisibility(View.VISIBLE);
        String init = new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + " " + Utils.getCurrentTime() + "的图文";
        edTitle.setText(init);
        directoryCode = getIntent().getStringExtra("directoryCode");
        if (Utils.isNull(directoryCode)) {
            directoryCode = new ShareUtils().getString(this, StaticClass.BELG_CATALOG_CODE, "");
            tvDirectory.setText(new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, ""));
        } else {
            tvDirectory.setText(getIntent().getStringExtra("directoryName"));
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new Adapter(this, list);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        if (NetUtils.isGPSEnabled(this)) {
            getPermissions();
            if (!Utils.isNull(mainCode)) {
                getTuwenDetail();
            }
        } else {
            showDialog();
        }
    }
    private void showDialog() {
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .asConfirm("提示", "定位服务未开启，请打开定位服务",
                        "取消", "去开启",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(intent);
                                finish();
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                finish();
                            }
                        }, false)
                .show();
    }
    private void startLoc() {
        //声明LocationClient类
        try {
            if(mLocationClient==null){
                LocationClient.setAgreePrivacy(true);
                mLocationClient = new LocationClient(getApplicationContext());
                LocationClientOption option = new LocationClientOption();
                mLocationClient.registerLocationListener(myListener);
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setIsNeedAddress(true);
                option.setOpenGps(true);
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
            }
            if(mLocationClient != null) {
                mLocationClient.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void getTuwenDetail() {
        Map<String, String> map = new HashMap<>();
        map.put("mainCode", mainCode);
        showLoading();
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.getTuwendetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {

                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        id = jsonObject1.getString("id");
                        edTitle.setText(jsonObject1.getString("title"));
                        String shareFStringlag = jsonObject1.getString("shareFlag");
                        if ("0".equals(shareFStringlag)) {
                            //不能分享，首先设置成1 然后点击的效果变成0
                            shareFlag = 1;
                        } else {
                            //能分享，首先设置成0 然后点击的效果变成1
                            shareFlag = 0;
                        }
                        JSONArray jsonArray = jsonObject1.getJSONArray("detailList");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            TuwenTypeEntity tuwenTypeEntity = new TuwenTypeEntity();
                            if (jsonObject2.getString("resourceType").equals("1")) {
                                tuwenTypeEntity.setResourceContent(jsonObject2.getString("resourceContent"));
                                tuwenTypeEntity.setItemType(1);
                            } else if (jsonObject2.getString("resourceType").equals("2")) {
                                tuwenTypeEntity.setImgUrl(jsonObject2.getString("resourceContent"));
                                tuwenTypeEntity.setResourceContent("");
                                tuwenTypeEntity.setId(System.currentTimeMillis() + "");
                                tuwenTypeEntity.setItemType(2);
                            } else if (jsonObject2.getString("resourceType").equals("3")) {
                                JSONObject jsonObject3 = jsonObject2.getJSONObject("resourceObject");
                                tuwenTypeEntity.setIsShare(jsonObject3.getString("shareFlag"));
                                tuwenTypeEntity.setWordSize(Utils.changeKM(jsonObject3.getString("dataSize")));
                                tuwenTypeEntity.setResourceContent(jsonObject3.getString("dataTitle"));
                                tuwenTypeEntity.setWordType(jsonObject3.getString("fileType"));
                                tuwenTypeEntity.setId(jsonObject3.getString("dataCode"));
                                tuwenTypeEntity.setItemType(3);
                            } else if (jsonObject2.getString("resourceType").equals("4")) {
                                JSONObject jsonObject3 = jsonObject2.getJSONObject("resourceObject");
                                tuwenTypeEntity.setIsShare(jsonObject3.getString("shareFlag"));
                                tuwenTypeEntity.setResourceContent(jsonObject3.getString("videoCoverPath"));
                                tuwenTypeEntity.setId(jsonObject3.getString("videoId"));
                                tuwenTypeEntity.setItemType(4);
                            }
                            if (tuwenTypeEntity != null) {
                                list.add(tuwenTypeEntity);
                            }
                        }
                        setShareFlag();
                        if (list.size() > 0) {
                            llAdd.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                            adapter.notifyDataSetChanged();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
            }
        });
    }

    private void getUrlData(String url, String timeId) {
        picInt++;
        File file = new File(url);
        MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "3", file, new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                JSONObject result = null;
                JSONObject data = null;
                try {
                    result = new JSONObject(response.body().toString());
                    if (result.getString("code").equals("200")) {
                        data = result.getJSONObject("data");
                        FileUtilss.delFile(url);
                        picInt--;
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getItemType() == 2 && list.get(i).getId().equals(timeId)) {
                                list.get(i).setImgUrl(data.getString("originalUrl"));
                            }
                        }
                        if (isUpload == 2 && picInt == 0) {
                            uploadData();
                        }
                    } else if (result.getString("code").startsWith("400")) {
                        OkGoUtil.onErrorIntent(result.getString("code"),result.getString("msg"));
                    }else{
                        MyToast.show(result.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (isUpload == 2) {
                        isUpload = 0;
                        dismissLoading();
                    }
                    MyToast.show("图片上传失败，请稍后重试");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (isUpload == 2) {
                    isUpload = 0;
                    dismissLoading();
                }
                MyToast.show("图片上传失败，请稍后重试");
            }
        });
    }

    private void uploadData() {
        List<Map<String, String>> uploadList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = new HashMap<>();
            if (list.get(i).getItemType() == 1) {
                map.put("resourceType", "1");
                map.put("resourceContent", list.get(i).getResourceContent());
            } else if (list.get(i).getItemType() == 2) {
                map.put("resourceType", "2");
                map.put("resourceContent", list.get(i).getImgUrl());
            } else if (list.get(i).getItemType() == 3) {
                map.put("resourceType", "3");
                map.put("resourceContent", list.get(i).getId());
            } else if (list.get(i).getItemType() == 4) {
                map.put("resourceType", "4");
                map.put("resourceContent", list.get(i).getId());
            }
            map.put("lvlNo", i + "");
            uploadList.add(map);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("title", edTitle.getText().toString());
        map.put("location", tvLocation.getText().toString());
        map.put("shareFlag", shareFlag);
        map.put("catalogCodes", directoryCode);
        map.put("detailList", XJson.listToJsArrays(uploadList));
        String url = "";
//        statusCd 状态(0 暂存 1提交 2通过 3不通过 )
        if (Utils.isNull(id)) {
            url = Urls.insertTuwen;
            if (isPreview) {
                //暂存
                map.put("statusCd", "0");
            } else {
                map.put("statusCd", "1");
            }
        } else {
            url = Urls.updateTuwen;
            map.put("id", id);
            map.put("mainCode", mainCode);
            if (isPreview) {
                //暂存
                map.put("statusCd", "0");
            } else {
                map.put("statusCd", "1");
            }
        }
        MyHttpRequest.postRequestJson(url, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    dismissLoading();
                    if ("200".equals(jsonObject.getString("code"))) {
                        isUpload = 3;
                        if (isPreview) {
                            //暂存成功  去预览
                            if (Utils.isNull(id)) {
                                JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                                id = jsonObject2.getString("id");
                                mainCode = jsonObject2.getString("mainCode");
                            }
                            isPreview = false;
                            if (saveTag == 0) {
                                MyToast.show("图文暂存成功");
                                String addressType = "";
                                if (Urls.baseUrl.contains("dev_kmer")) {
                                    addressType = "1";
                                } else {
                                    addressType = "0";
                                }
                                String url = Urls.tuwenDetail + "mainCode=" + mainCode + "&token=" + Token.INSTANCE.getToken() + "&statusHeight=" + Utils.getStatusBarHeightDp(PublishTuwensActivity.this) + "&time=" + System.currentTimeMillis() + "&addressType=" + addressType;
                                Intent intent = new Intent(PublishTuwensActivity.this, WebCommonActivity.class);
                                intent.putExtra("url", url);
                                intent.putExtra("title", "预览");
                                intent.putExtra("isTuwen", 1);
                                intent.putExtra("waterMark", "13");
                                startActivity(intent);
                            } else if (saveTag == 2) {
                                MyToast.show("图文保存成功");
                                finish();
                            } else {
                                MyToast.show("图文暂存成功");
                            }
                        } else {
                            finish();
                            MyToast.show("发布成功");
                        }
                    } else {
                        isUpload = 4;
                        isPreview = false;
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    isUpload = 4;
                    isPreview = false;
                    MyToast.show("发布失败，请稍后重试");

                }
            }
        });
    }

    private void getPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            startLoc();
                        } else {
                            MyToast.show("定位权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            MyToast.show("被永久拒绝授权，请手动授予定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(PublishTuwensActivity.this, permissions);
                        } else {
                            MyToast.show("获取定位权限失败");
                        }
                    }
                });
    }

    private int locationFlag = 0;

    private void toStart() {
        showLoading();
        if (picInt == 0) {
            //开始上传
            isUpload = 1;
            uploadData();
        } else {
            //图片还在上传中，等上传结束在继续调用接口
            isUpload = 2;
        }
    }

    private void setShareFlag() {
        if (shareFlag == 1) {
            shareFlag = 0;
            ivBg.setVisibility(View.GONE);
            ivChoice.setVisibility(View.GONE);
            ivChoice2.setVisibility(View.VISIBLE);
        } else {
            shareFlag = 1;
            ivBg.setVisibility(View.VISIBLE);
            ivChoice.setVisibility(View.VISIBLE);
            ivChoice2.setVisibility(View.GONE);
        }
    }

    private void toStag() {
        //暂存
        if (Urls.antiShake.check()) {
            return;
        }
        if (edTitle == null) {
            return;
        }
        if (Utils.isNull(edTitle.getText().toString().replace(" ", ""))) {
            if (saveTag == 2) {
                finish();
            } else {
                MyToast.show("请输入标题");
            }
            return;
        }
        if (list.size() == 0) {
            if (saveTag == 2) {
                finish();
            } else {
                MyToast.show("请添加内容");
            }
            return;
        }
        isPreview = true;
        toStart();
    }

    @OnClick({R.id.common_title_back, R.id.tvChoieDirectory, R.id.tv_save, R.id.common_right_iv_ll, R.id.rlChoice, R.id.llAdd, R.id.tvChoieLocation, R.id.tv_publish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                toFinish();
                break;
            case R.id.tvChoieDirectory:
                Intent intent = new Intent(this, VideoNewCatesActivity.class);
                intent.putExtra("videoType", "7");
                startActivity(intent);
                break;
            case R.id.common_right_iv_ll:
                saveTag = 0;
                toStag();
                break;
            case R.id.tv_save:
                saveTag = 1;
                toStag();
                break;
            case R.id.llAdd:
                new TuwenBottomDialog(this, new HomeBottomDialogListener() {
                    @Override
                    public void onListItemClick(int position) {
                        isEdit = false;
                        addTuwenData(position);
                    }
                }).show();
                break;
            case R.id.tvChoieLocation:
                getPermissions();
                break;
            case R.id.rlChoice:
                if (ivBg == null) {
                    return;
                }
                if (!dataNoShare) {
                    MyToast.show("图文中含有不能分享的文件");
                } else {
                    setShareFlag();
                }
                break;
            case R.id.tv_publish:
                if (Urls.antiShake.check()) {
                    return;
                }

                if (edTitle == null) {
                    return;
                }
                if (Utils.isNull(edTitle.getText().toString().replace(" ", ""))) {
                    MyToast.show("请输入标题");
                    return;
                }
                if (list.size() == 0) {
                    MyToast.show("请添加内容");
                    return;
                }
                toStart();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        toFinish();
    }

    private void toFinish() {
        if (isUpload == 1 || isUpload == 2) {
            MyToast.show("正在发布中，请稍后");
        } else {
            initTuwenDialog();
        }
    }

    private void initTuwenDialog() {
        new android.app.AlertDialog.Builder(this)
                .setPositiveButton("保存并退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        saveTag = 2;
                        toStag();
                    }
                })
                .setNegativeButton("不保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .setMessage("图文正在编辑中")
                .setTitle("提示")
                .show();

    }

    private void requestCamera() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {

                            openCamera();
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(PublishTuwensActivity.this, denied, quick);
                    }
                });
    }

    private void openCamera() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .isDisplayCamera(true)//是否显示相机入口
                .setMaxSelectNum(1)
                .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                .isPreviewImage(true)//是否支持预览图片
                .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                String url = "";
                if (!Utils.isNull(selectList.get(0).getCompressPath())) {
                    if (selectList.get(0).getCompressPath().contains("content://")) {
                        Uri uri = Uri.parse(selectList.get(0).getCompressPath());
                        url = PathUtil.getPath(this, uri);
                    } else {
                        url = selectList.get(0).getCompressPath();
                    }
                } else {
                    if (selectList.get(0).getPath().contains("content://")) {
                        Uri uri = Uri.parse(selectList.get(0).getPath());
                        url = PathUtil.getPath(this, uri);
                    } else {
                        url = selectList.get(0).getPath();
                    }
                }
                Log.i("jiaa", url);
                if (!Utils.isNull(url)) {
                    String id = System.currentTimeMillis() + "";
                    TuwenTypeEntity tuwenTypeEntity = new TuwenTypeEntity();
                    tuwenTypeEntity.setResourceContent(url);
                    tuwenTypeEntity.setId(id);
                    tuwenTypeEntity.setItemType(2);
                    setSort(tuwenTypeEntity);
                    getUrlData(url, id);
                } else {
                    MyToast.show("图片选择异常，请重新选择");
                }
            }
        }
        if (data == null) {
            return;
        }
        KLog.i(requestCode + "----");
        if (requestCode == 1001) {
            TuwenTypeEntity tuwenTypeEntity = new TuwenTypeEntity();
            tuwenTypeEntity.setResourceContent(data.getStringExtra("content"));
            tuwenTypeEntity.setItemType(1);
            setSort(tuwenTypeEntity);
        } else if (requestCode == 1003) {
            TuwenTypeEntity tuwenTypeEntity = new TuwenTypeEntity();
            tuwenTypeEntity.setIsShare(data.getStringExtra("isShare"));
            tuwenTypeEntity.setWordSize(data.getStringExtra("size"));
            tuwenTypeEntity.setResourceContent(data.getStringExtra("name"));
            tuwenTypeEntity.setWordType(data.getStringExtra("wordType"));
            tuwenTypeEntity.setId(data.getStringExtra("dataCode"));
            tuwenTypeEntity.setItemType(3);
            setSort(tuwenTypeEntity);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("id") && map.containsKey("url")) {
                TuwenTypeEntity tuwenTypeEntity = new TuwenTypeEntity();
                tuwenTypeEntity.setIsShare(map.get("isShare"));
                tuwenTypeEntity.setResourceContent(map.get("url"));
                tuwenTypeEntity.setId(map.get("id"));
                tuwenTypeEntity.setItemType(4);
                setSort(tuwenTypeEntity);

            } else if (map.containsKey("videoCate") && map.containsKey("videoNames")) {
                //选择提目录
                if (tvDirectory == null) {
                    return;
                }
                directoryCode = map.get("videoCate");
                tvDirectory.setText(map.get("videoNames"));
            }
        }
    }

    private void setSort(TuwenTypeEntity tuwenTypeEntity) {
        recyclerView.setVisibility(View.VISIBLE);
        llAdd.setVisibility(View.GONE);
        //处理排序
        if (isEdit) {
            //修改
            list.add(index, tuwenTypeEntity);
            list.remove(index + 1);
            isEdit = false;
            adapter.notifyItemChanged(index);
        } else {
            if (sort) {
                //向上插入
                list.add(index, tuwenTypeEntity);
                adapter.notifyItemRangeChanged(index, list.size() - index);
            } else {
                //向下插入
                if (list.size() == 0) {
                    //当前数组为0，新增第一个
                    list.add(tuwenTypeEntity);
                    adapter.notifyDataSetChanged();
                } else {
                    if (index + 1 > list.size() - 1) {
                        //如果是最后一个，直接新增
                        list.add(tuwenTypeEntity);
                        adapter.notifyItemChanged(index + 1);
                    } else {
                        //不是最后一个新增
                        list.add(index + 1, tuwenTypeEntity);
                        adapter.notifyItemRangeChanged(index + 1, list.size() - index - 1);
                    }
                }
            }
        }
        //重新过滤数据，看是否有不能分享的文件
        setShareData();
    }

    private void setShareData() {
        dataNoShare = true;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getItemType() == 3 || list.get(i).getItemType() == 4) {
                //                shareFlag;//是否允许分享(0-否 1-是)'
                if (list.get(i).getIsShare().equals("0")) {
                    dataNoShare = false;
                    shareFlag = 1;
                    setShareFlag();
                }
            }
        }
    }

    private void addTuwenData(int position) {
        if (position == 1) {
            Intent intent = new Intent(PublishTuwensActivity.this, TuwenTxtActivity.class);
            if (isEdit) {
                intent.putExtra("content", list.get(index).getResourceContent());
            }
            startActivityForResult(intent, 1001);
        } else if (position == 2) {
            requestCamera();
        } else if (position == 3) {
            Intent intent = new Intent(PublishTuwensActivity.this, DocumentSearchActivity.class);
            intent.putExtra("type", 2);
            startActivityForResult(intent, 1003);
        } else if (position == 4) {
            Intent intent = new Intent(PublishTuwensActivity.this, VideoSearchActivity.class);
            intent.putExtra("type", 2);
            startActivityForResult(intent, 1004);
        }
    }

    AttachPopupView attachPopupView;

    class Adapter extends BaseMultiItemQuickAdapter<TuwenTypeEntity,
            BaseViewHolderEx> {
        private Context mContext;
        private RequestOptions options_video;
        private int screenWidth, picWidth;//单张图片宽度，两张图片时图片的边长
        private String userId = "";//登陆者id

        public Adapter(Context mContext, List<TuwenTypeEntity> data) {
            super(data);
            this.mContext = mContext;
            //1文本 2图片 3资料 4视频
            addItemType(1, R.layout.item_tuwen_publish_txt);
            addItemType(2, R.layout.item_tuwen_publish_pic);
            addItemType(3, R.layout.item_tuwen_publish_word);
            addItemType(4, R.layout.item_tuwen_publish_video);
        }

        @Override
        protected void convert(BaseViewHolderEx helper, TuwenTypeEntity contentBean) {
            LinearLayout llMore = helper.getView(R.id.llMore);
            ImageView ivMore = helper.getView(R.id.ivMore);
            switch (helper.getItemViewsType()) {
                case 1:
                    TextView tvContent = helper.getView
                            (R.id.tvContent);
                    tvContent.setText(contentBean.getResourceContent());
                    break;
                case 2:
                    ImageView imageView = helper.getView
                            (R.id.ivContent);
                    if (!Utils.isNull(contentBean.getResourceContent())) {
                        Glide.with(PublishTuwensActivity.this).load(contentBean.getResourceContent()).into(imageView);
                    } else {
                        Glide.with(PublishTuwensActivity.this).load(contentBean.getImgUrl()).into(imageView);
                    }
                    KLog.i(contentBean.getResourceContent() + "--" + contentBean.getImgUrl());
                    break;
                case 3:
//                    文件类型1--word 2 --excel 3--PPT  4pdf
                    ImageView ivType = helper.getView(R.id.ivType);
                    RelativeLayout rlBg = helper.getView(R.id.rlBg);
                    TextView tvName = helper.getView(R.id.tvName);
                    TextView tvSize = helper.getView(R.id.tvSize);
                    TextView tvInit = helper.getView(R.id.tvInit);
                    tvName.setText(contentBean.getResourceContent());
                    tvSize.setText(contentBean.getWordSize());
                    if ("0".equals(contentBean.getIsShare())) {
                        tvInit.setVisibility(View.VISIBLE);
                        rlBg.setBackgroundResource(R.drawable.shape_main_color_2f_2);
                    } else {
                        tvInit.setVisibility(View.GONE);
                        rlBg.setBackgroundResource(R.drawable.shape_fcfcfc_2);
                    }
                    if ("1".equals(contentBean.getWordType())) {
                        Glide.with(PublishTuwensActivity.this).load(R.drawable.icon_preview_word).into(ivType);
                    } else if ("2".equals(contentBean.getWordType())) {
                        Glide.with(PublishTuwensActivity.this).load(R.drawable.icon_preview_excel).into(ivType);
                    } else if ("3".equals(contentBean.getWordType())) {
                        Glide.with(PublishTuwensActivity.this).load(R.drawable.icon_preview_ppt).into(ivType);
                    } else if ("4".equals(contentBean.getWordType())) {
                        Glide.with(PublishTuwensActivity.this).load(R.drawable.icon_preview_pdf).into(ivType);
                    } else {
                        Glide.with(PublishTuwensActivity.this).load(R.drawable.icon_file_default).into(ivType);
                    }
                    break;
                case 4:
                    ImageView ivVideo = helper.getView(R.id.ivVideo);
                    ImageView ivBg = helper.getView(R.id.ivBg);
                    TextView tvVideoInit = helper.getView(R.id.tvInit);
                    Glide.with(PublishTuwensActivity.this).load(contentBean.getResourceContent()).into(ivVideo);
                    if ("0".equals(contentBean.getIsShare())) {
                        tvVideoInit.setVisibility(View.VISIBLE);
                        ivBg.setBackgroundResource(R.drawable.shape_000_4f_2);
                    } else {
                        tvVideoInit.setVisibility(View.GONE);
                        ivBg.setBackgroundResource(R.drawable.shape_000_2f_2);
                    }
                    break;

            }
            llMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    attachPopupView = new XPopup.Builder(getContext())
                            .hasShadowBg(false)
                            .isClickThrough(true)
//                            .popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                            .atView(ivMore)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                            .asAttachList(new String[]{"向上插入", "向下插入", "编辑", "删除"},
                                    new int[]{R.drawable.iv_up_40, R.drawable.iv_down_40, R.drawable.iv_edit_40, R.drawable.iv_delete_40},
                                    new OnSelectListener() {
                                        @Override
                                        public void onSelect(int position, String text) {
                                            if (position == 0) {
                                                sort = true;
                                                new TuwenBottomDialog(PublishTuwensActivity.this, new HomeBottomDialogListener() {
                                                    @Override
                                                    public void onListItemClick(int position) {
                                                        isEdit = false;
                                                        index = helper.getItemPosition();
                                                        addTuwenData(position);
                                                    }
                                                }).show();
                                            } else if (position == 1) {
                                                sort = false;
                                                new TuwenBottomDialog(PublishTuwensActivity.this, new HomeBottomDialogListener() {
                                                    @Override
                                                    public void onListItemClick(int position) {
                                                        isEdit = false;
                                                        index = helper.getItemPosition();
                                                        addTuwenData(position);
                                                    }
                                                }).show();
                                            } else if (position == 2) {
                                                isEdit = true;
                                                index = helper.getItemPosition();
                                                addTuwenData(contentBean.getItemType());
                                            } else if (position == 3) {
                                                list.remove(helper.getItemPosition());
                                                if (list.size() == 0) {
                                                    index = -1;
                                                    llAdd.setVisibility(View.VISIBLE);
                                                    recyclerView.setVisibility(View.GONE);
                                                } else {
                                                    index = list.size() - 1;
                                                    llAdd.setVisibility(View.GONE);
                                                    recyclerView.setVisibility(View.VISIBLE);
                                                    adapter.notifyItemRemoved(helper.getItemPosition());
                                                    adapter.notifyItemRangeChanged(position, list.size() - helper.getItemPosition());
                                                }
                                                //重新过滤数据，看是否有不能分享的文件
                                                setShareData();
                                            }
                                        }
                                    }, 0, 0, Gravity.LEFT);
                    ;
                    attachPopupView.show();
                }
            });
        }

    }
    private boolean firstLocation=true;
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                locationFlag++;
                if (tvLocation == null) {
                    return;
                }
                if (!Utils.isNull(location.getAddrStr())) {
                    tvLocation.setText(location.getAddrStr());
                }else {
                    if(firstLocation){
                        if (mLocationClient != null) {
                            firstLocation=false;
                            mLocationClient.start();
                        }
                    }
                }
                if (locationFlag > 3) {
                    if (null != mLocationClient && mLocationClient.isStarted()) {
                        locationFlag = 0;
                        if(mLocationClient!=null){
                            mLocationClient.stop();
                        }
                    }
                }
            }else {
                if(firstLocation){
                    if (mLocationClient != null) {
                        firstLocation=false;
                        mLocationClient.start();
                    }
                }
            }


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLocationClient!=null){
            mLocationClient.stop();
        }
    }
}
